<?php

/*
 * 依设定日期跟新门店和公司
 */

$serverFilePath = $_SERVER["SCRIPT_FILENAME"]; ;//realpath(dirname(__FILE__)); //$_SERVER["SCRIPT_FILENAME"];
$doc_dir = strrpos($serverFilePath, '/crontab');
$doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root 
include_once $doc_dir . '/config/lib/Config.php';
include_once $doc_dir . '/plugin/Wechat/Wechat.php';
include_once $doc_dir . '/plugin/WechatMsgTemplate.php';
include_once $doc_dir . '/plugin/Logging.php';

set_time_limit(0);
error_reporting(E_ALL);
header("Content-type:text/html;charset:utf-8");

$log = new Logging();
$log->lfile('pushRiders_wx');
$config_ini = $doc_dir . 'config/config.ini';

$ini_array = parse_ini_file($config_ini, true);
$db_array = $ini_array['DB'];
$getWebsite = $ini_array['WebSite'];
$getWechat = $ini_array['WECHAT'];

$con = mysqli_init();
mysqli_real_connect($con, $db_array['host'], $db_array['id'], $db_array['pwd'], $db_array['database'], $db_array['port']);
mysqli_set_charset($con, $db_array['encoding']);
# 11-04 确认 推送所有自建骑手 接单后 订单收货时间小于等于30分钟 推送超时通知给骑手
//$sql = "SELECT a.*,b.express_mobile,b.shop_delivery_time FROM orders as a LEFT JOIN orders_express as b ON a.ph_no = b.ph_no WHERE a.status = 3 AND a.isdeleted = 0 AND a.express_type = 'self' AND a.ispush = 0 AND b.express_type = 'self' AND b.status = 3 AND a.ph_no = 'PH19061200000048'";
$sql = "SELECT a.*,b.express_mobile FROM orders as a LEFT JOIN orders_express as b ON a.ph_no = b.ph_no WHERE (a.status = 3 OR a.status = 4 ) AND a.isdeleted = 0 AND a.express_type = 'self' AND a.ispush = 0 AND b.express_type = 'self' AND  (b.status = 3 OR b.status = 4 )";
$result = mysqli_query($con, $sql);
foreach($result as $r){
    if($r && count($r) > 0){
        $dtime = strtotime($r['shop_delivery_time']);
        $startdate = strtotime(date('Y-m-d H:i:s'));
        $mins = timediff($dtime,$startdate);
        if($mins > 30){
            continue;
        }
        $id = $r['id'];
        # 微信通知
        $RidersID = $r['express_mobile'];   # 骑手手机号
        $url = $getWebsite['website_url'].'?md=service&cl=api&at=member&mobile='.$RidersID;
        $userInfo = getCurl($url);
        $userInfo = json_decode($userInfo,true);
        //微信信息推送
        $first = '您有一笔订单，即将配送超时！';
        $PushInfo['keyword1'] = '订单超时';
        $PushInfo['keyword2'] = $r['order_no'];
        $PushInfo['keyword3'] = date('Y-m-d H:i:s');
        $remark = '剩余时间还有30分钟，请您尽量完成配送！';
        $template_id = $getWechat['push_order_status_ID']; # 微信模板
        $openid = $userInfo['data']['openID'];
        $url = $getWebsite['website_url'] . '?md=riders&cl=riders&at=regriders';
        $options = array(
            'token' => $getWechat["token"],// "o5Dttg7seGr7n8G8bu3r", //$config["token"], // 填写你设定的key
            'encodingaeskey' => $getWechat["encodingaeskey"],//'IZqYmURuhaEThWh4D9GEqR08ILWfwe0PVal5AJ7IyxD', // 填写加密用的EncodingAESKey
            'appid' => $getWechat["appid"],// 'wx33ef06b1e938bc90', // 'wx32e0fc7be8ddb657', // 填写高级调用功能的app id
            'appsecret' => $getWechat["appsecret"],//'c7c9a1ecdd754c3bd9b2db5b3d1d6df5', //eb2d791c55d371b103aaf2d8a8dd36f4', // 填写高级调用功能的密钥
            'debug' => true
        );
        $wechat_class = new Wechat($options);
        $wechat_msg = WechatMsgTemplate::pushTimeOut($first,$PushInfo,$remark,$template_id, $openid, $url);
        $wechat_result = $wechat_class->sendMessageByTemplate($wechat_msg);
        $sql = "update orders set ispush = 1 WHERE id =  $id";
        $result = mysqli_query($con, $sql);
        $log->lwrite(date('Y-m-d H:i:s').',pushInfo：'.$RidersID.'---'.$r['order_no'].'---'.json_encode($wechat_result, JSON_UNESCAPED_UNICODE));
    }
}

function timediff($begin_time,$end_time)
{
    if($begin_time < $end_time){
        $starttime = $begin_time;
        $endtime = $end_time;
    }else{
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime-$starttime;
    $remain = $timediff%86400;
    $remain = $remain%3600;
    $mins = intval($remain/60);
    return $mins;
}

function getCurl($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result =  curl_exec($ch);
    curl_close ($ch);
    return $result;
}

//订单处理超时提醒
//您有一笔订单，即将配送超时！
//业务类型：订单超时
//订单编号：PH18103000000637
//提醒时间：2019-10-10 11:20
//剩余时间还有30分钟，请您尽量完成配送！
function insertValue($arr) {
    $keys = array();
    $values = array();

    foreach ($arr as $k => $val) {
        $keys[] = "`" . $k . "`";
        $values[] = "'" . $val . "'";
    }
    $ks = implode(",", $keys);
    $vals = implode(",", $values);
    $re = "(" . $ks . ", createdt) values (" . $vals . ", now())";

    return $re;
}

function updateValue($arr) {
    $result = array();
    foreach ($arr as $k => $val) {
        $result[] = "`" . $k . "`" . "='" . $val . "'";
    }
    $result[] = "`updatedt`" . "=now() ";

    $re = implode(",", $result);
    return $re;
}

 function mysql_escape($content) {
    if (!get_magic_quotes_gpc()) {

        if (is_array($content)) {
            foreach ($content as $key => $value) {
                $content[$key] = addslashes($value);
            }
        } else {
            $content = addslashes($content);
        }
    }
    return $content;
}
?>

